﻿using UnityEngine;

public class NormalsReplacementShader : MonoBehaviour
{
    [SerializeField]
    Shader normalsShader;

    private RenderTexture renderTexture;
    private new Camera camera;

    private void Start()
    {
        Camera thisCamera = GetComponent<Camera>();

        // 创建一个和相机可见大小相同的纹理
        renderTexture = new RenderTexture(thisCamera.pixelWidth, thisCamera.pixelHeight, 24);
        // 将此纹理设置到全局变量“_cameraNormalsTexture”中，方便任何Shader都可以访问
        Shader.SetGlobalTexture("_CameraNormalsTexture", renderTexture);

        // 拷贝一个相机，属性参数和场景主相机想鸥汀
        GameObject copy = new GameObject("Normals camera");
        camera = copy.AddComponent<Camera>();
        camera.CopyFrom(thisCamera);
        camera.transform.SetParent(transform);
        // 将此相机看到的图像渲染到刚刚新建的RT上
        camera.targetTexture = renderTexture;
        // 使用法线Shader进行渲染，此Shader会返回物体表面的法线值作为输出的颜色
        camera.SetReplacementShader(normalsShader, "RenderType");
        // depth减1，保证在主相机之前渲染
        camera.depth = thisCamera.depth - 1;
    }
}
